package com.richbond.sdjdsm.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.richbond.sdjdsm.util.DBHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * 货物类型
 * Created by LiWenxun on 2016/1/4.
 */
public class GoodsTypeDao {
    private String table_name = DBHelper.TABLE_GOODS_TYPE;
    private static final String TAG = GoodsTypeDao.class.getSimpleName();
    public static final String INIT_DATA = "INSERT INTO goods_type(name) VALUES('数码相机');";
    DBHelper helper = null;

    public GoodsTypeDao(Context cxt) {
        helper = new DBHelper(cxt);
    }

    /**
     * 当Activity中调用此构造方法，传入一个版本号时，系统会在下一次调用数据库时调用Helper中的onUpgrade()方法进行更新
     *
     * @param cxt
     * @param version
     */
    public GoodsTypeDao(Context cxt, int version) {
        helper = new DBHelper(cxt, version);
    }

    // 插入操作
    public boolean insertData(String name) {
        long isSucceed;
        SQLiteDatabase db = helper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("name", name);

        isSucceed = db.insert(table_name, null, values);
        db.close();
        return isSucceed > 0;
    }

    // 查询操作
    public List<String> findData() {
        List<String> list = new ArrayList<>();
        String sql = "select * from " + table_name;
        SQLiteDatabase db = helper.getWritableDatabase();
        Cursor cursor = db.rawQuery(sql, null);
        while (cursor.moveToNext()) {
            //String name = cursor.getString(0); //获取第一列的值,第一列的索引从0开始
            String name = cursor.getString(cursor.getColumnIndex("name")); //
            list.add(name);
            Log.v(TAG, "我是" + list.size() + name);
        }
        cursor.close();
        db.close();
        return list;
    }

    // 查询操作
    public List<String> findDataByWord(String keyWord) {
        List<String> list = new ArrayList<String>();
        String sql = "select * from " + table_name + " where (name like '%" + keyWord + "%')";
        SQLiteDatabase db = helper.getWritableDatabase();
        Cursor cursor = db.rawQuery(sql, null);
        while (cursor.moveToNext()) {
            //String name = cursor.getString(0); //获取第一列的值,第一列的索引从0开始
            String name = cursor.getString(cursor.getColumnIndex("name")); //
            list.add(name);
            Log.v(TAG, "我是" + list.size() + name);
        }
        cursor.close();
        db.close();
        return list;
    }

    //删除操作
    public boolean deleteByName(String name) {
        SQLiteDatabase db = helper.getWritableDatabase();
        int isDelete;
        String[] args;
        args = new String[]{String.valueOf(name)};
        isDelete = db.delete(table_name, "name=?", args);
        return isDelete > 0;
    }
}
